/**
 * 
 */
package com.shuqi.activity.Fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shuqi.activity.ActivityManager;
import com.shuqi.activity.BookSearchParentActivity;
import com.shuqi.activity.BookSearchResultActivity;
import com.shuqi.activity.adapter.BookSearchRanklistAdapter;
import com.shuqi.activity.viewport.SearchListView;
import com.shuqi.activity.viewport.SearchListView.OnCloseAndOpenListener;
import com.shuqi.activity.viewport.SearchRankFooterView;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.LocalBookInfoManager;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.BookSearchRankController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.SearchHistoryDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.SearchRecommendInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * @author linyuren
 * 
 */
public class BookSearchAllFragment extends FragmentBase implements IEventListener,
        HttpRequestErrListener, OnClickListener {

    private final String Tag = "BookSearchAllFragment";

    private final static int init = EventTypeConstants.BASE;
    private final static int showCache = init + 1;
    private final static int initDataRankSuccess = init + 2;;
    private final static int show_404 = init + 3;

    ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case init:
                    fragmentLogicForward();
                    break;
                case initDataRankSuccess:
                    fragmentInitData();
                    break;
                case showCache:
                    loadingLayout.setVisibility(View.GONE);
                    readLocalRankDdata();
                    break;
                case show_404:
                    act_nonetwork.setVisibility(View.VISIBLE);
                    // mContext.showMsg("网络异常..");
                    break;
                default:
                    break;
            }
        };
    };

    private BookSearchParentActivity mContext;

    /** 搜索排行Controller */
    private BookSearchRankController rankController;

    /** 搜索主页排行列表适配器 */
    private BookSearchRanklistAdapter bookSearchRanklistAdapter;

    /** 存放排行列表 数据 */
    private List<BookInfo> searchRankInfoData = new ArrayList<BookInfo>();

    /** 每次显示20条排行数据 */
    private final int showRankCurrentNum = 20;

    /** 当前显示的排行页数 */
    private int shouRankCurrentPage = 0;

    /** 当前界面布局 */
    private View curretntLayout;

    /** 当前listview */
    private SearchListView search_rankinglist;

    /** 进度圈 */
    private LinearLayout loadingLayout;

    /** 网络错误 */
    private View act_nonetwork;

    /** 无数据 */
    private LinearLayout mActNoDataView;

    /** 搜索排行的页脚 */
    private SearchRankFooterView rankFooterView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        this.rankController =
                (BookSearchRankController) MainController.getMainManagerInstance()
                        .createController(MainController.CONTROLLER_ID_BOOKSEARCH, mContext);
        this.rankController.addEventListener(this);

        if (container == null) {
            return null;
        }
        if (inflater == null) {
            inflater = LayoutInflater.from(mContext);
        }
        // 第一次实例化,bundle为传入参数
        if (savedInstanceState == null) {
            savedInstanceState = getArguments();
        }
        curretntLayout = inflater.inflate(R.layout.book_search_rank_content, container, false);

        handler.sendEmptyMessage(init);
        return curretntLayout;
    }

    @Override
    public void onAttach(Activity activity) {
        if (mContext == null) {
            mContext = (BookSearchParentActivity) activity;
        }
        super.onAttach(activity);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPageSelected() {
        if (searchRankInfoData == null || searchRankInfoData.size() == 0) {
            mRequestData();
        } else {
            return;
        }
        super.onPageSelected();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.retry:
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
                    @Override
                    public void netErrorCallback() {
                        if (!Util.isNetworkConnected(mContext)) {
                            return;
                        }
                        mRequestData();
                    }
                });
                break;
        }
    }

    @Override
    public void fragmentLogicForward() {
        init();
        setListViewListener();
        StatisticsUtils.onEvent(mContext, StatisticsEventID.BOOKSEARCH_ALL);
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:// 读取数据 写处理逻辑
                SearchRecommendInfo srInfo = (SearchRecommendInfo) data;
                List<BookInfo> InfoData = srInfo.getBooksList();
                if (InfoData != null && InfoData.size() > 0) {
                    this.searchRankInfoData.clear();
                    this.tempRankInfoData.clear();

                    for (int i = 0; i < InfoData.size(); i++) {
                        BookInfo info = InfoData.get(i);
                        if (i == 0) {
                            info.setSourceId("1");
                        } else if (i == 1) {
                            info.setSourceId("2");
                        } else if (i == 2) {
                            info.setSourceId("3");
                        } else {
                            info.setSourceId("");
                        }
                        this.searchRankInfoData.add(info);
                    }
                    // 保存数据到本地
                    LocalBookInfoManager.getInstance().saveBookInfo2Local(this.searchRankInfoData,
                            LocalBookInfoManager.getInstance().getmBookSearchAllLocalDataName());
                }
                handler.sendEmptyMessage(initDataRankSuccess);
                break;
            default:
                Log4an.e(Tag, "加载失败。。。");
                handler.sendEmptyMessage(showCache);
                break;
        }
    }

    @Override
    public void fragmentInitData() {
        showUpdate();
        showRankListData(shouRankCurrentPage);
    }

    /** 初始化 */
    private void init() {
        search_rankinglist = (SearchListView) curretntLayout.findViewById(R.id.search_rankinglist);
        rankFooterView = new SearchRankFooterView(mContext);

        act_nonetwork = (View) curretntLayout.findViewById(R.id.include_error);
        loadingLayout = (LinearLayout) curretntLayout.findViewById(R.id.include_loading);
        act_nonetwork.findViewById(R.id.retry).setOnClickListener(this);

        mActNoDataView = (LinearLayout) curretntLayout.findViewById(R.id.nodata_layout);

    }

    /** 设置listview事件监听 */
    private void setListViewListener() {
        search_rankinglist.setOnItemClickListener(new myOnItemClickListener());// 设置排行列表监听
        search_rankinglist.setOnScrollListener(new rankListOnScrollListener());

        search_rankinglist.setOnCloseAndOpenListener(new OnCloseAndOpenListener() {
            @Override
            public boolean open() {
                if (!((BookSearchParentActivity) mContext).mGetIsShowSearchBox()) {
                    return ((BookSearchParentActivity) mContext).mChangeSearchBoxStates();
                } else {
                    return false;
                }
            }

            @Override
            public boolean close() {
                if (((BookSearchParentActivity) mContext).mGetIsShowSearchBox()) {
                    return ((BookSearchParentActivity) mContext).mChangeSearchBoxStates();
                } else {
                    return false;
                }
            }
        });
    }

    /** 读取本地热搜排行数据 */
    private void readLocalRankDdata() {
        this.searchRankInfoData =
                LocalBookInfoManager.getInstance().readLocal2BookInfo(
                        LocalBookInfoManager.getInstance().getmBookSearchAllLocalDataName());

        if (this.searchRankInfoData == null || this.searchRankInfoData.size() == 0) {
            this.searchRankInfoData = new ArrayList<BookInfo>();
            handler.sendEmptyMessage(show_404);
        } else {
            showUpdate();
            tempRankInfoData.clear();
            showRankListData(shouRankCurrentPage);
        }
    }

    /**
     * 更新提示
     */
    private void showUpdate() {
        if (search_rankinglist.getFooterViewsCount() == 0
                && this.searchRankInfoData.size() > showRankCurrentNum) {
            search_rankinglist.addFooterView(rankFooterView);
        }
    }

    /** 关闭提示 */
    private void hideUpData() {
        if (search_rankinglist.getFooterViewsCount() > 0) {
            rankFooterView.findViewById(R.id.footer_show_dialog).setVisibility(View.GONE);
            rankFooterView.findViewById(R.id.footer_back).setVisibility(View.VISIBLE);
            rankFooterView.findViewById(R.id.footer_back).setBackgroundColor(
                    getResources().getColor(android.R.color.transparent));
            ((TextView) rankFooterView.findViewById(R.id.footer_content)).setText("已加载全部");
        }
    }

    /** 请求数据 */
    private void mRequestData() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
        rankController.handle(0, "rank", "7");
    }

    /** 搜索排行列表点击事件 */
    private class myOnItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BookInfo info = searchRankInfoData.get(position);
            Intent intent = new Intent(mContext, BookSearchResultActivity.class);
            intent.putExtra("keyword", info.getBookName());
            SearchHistoryDao.getInstance().saveSearchHistory(info.getBookName()); // 保存到数据库
            ActivityManager.getInstance().startNextActivity(intent, mContext.getParent());
        }

    }

    /** 搜索排行滑到底部加载更多数据 */
    private class rankListOnScrollListener implements OnScrollListener {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                int totalItemCount) {

        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (view.getLastVisiblePosition() == (view.getCount() - 1)) {

                rankFooterView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rankFooterView.findViewById(R.id.footer_back).setVisibility(View.GONE);
                        rankFooterView.findViewById(R.id.footer_show_dialog).setVisibility(
                                View.VISIBLE);
                        shouRankCurrentPage++;
                        showRankListData(shouRankCurrentPage);
                    }
                });
            }
        }

    }

    // 临时集合
    private List<BookInfo> tempRankInfoData = new ArrayList<BookInfo>();

    /** 显示收到的搜索排行数据 */
    private void showRankListData(int curretnPage) {
        for (int i = curretnPage * showRankCurrentNum; i < (curretnPage + 1) * showRankCurrentNum
                && i < this.searchRankInfoData.size(); i++) {
            BookInfo tempInfo = this.searchRankInfoData.get(i);
            tempRankInfoData.add(tempInfo);
        }
        if (tempRankInfoData.size() >= this.searchRankInfoData.size()) {
            hideUpData();
        }
        if (this.bookSearchRanklistAdapter == null) {
            this.bookSearchRanklistAdapter = new BookSearchRanklistAdapter(mContext);
            this.bookSearchRanklistAdapter.setRanklistAdapter(tempRankInfoData);
            this.search_rankinglist.setAdapter(this.bookSearchRanklistAdapter);
        } else {
            this.bookSearchRanklistAdapter.setRanklistAdapter(tempRankInfoData);
            this.rankFooterView.findViewById(R.id.footer_back).setVisibility(View.VISIBLE);
            this.rankFooterView.findViewById(R.id.footer_show_dialog).setVisibility(View.GONE);
        }

        if (tempRankInfoData == null || tempRankInfoData.size() == 0) { // 如果没有数据显示无数据提示
            mActNoDataView.setVisibility(View.VISIBLE);
        } else {
            mActNoDataView.setVisibility(View.GONE);
        }

        this.loadingLayout.setVisibility(View.GONE);
        this.act_nonetwork.setVisibility(View.GONE);
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }


}
